module Wechatpay
  module DecryptV3
    def decrypt_v3(ciphertext, associated_data, nonce)
      # Decode base64 ciphertext
      cipher_data = Base64.decode64(ciphertext)

      # Get the auth tag (last 16 bytes)
      auth_tag = cipher_data[-16..]
      cipher_text = cipher_data[0...-16]

      # Initialize cipher
      cipher = OpenSSL::Cipher.new('aes-256-gcm')
      cipher.decrypt
      cipher.key = @client.v3_key
      cipher.iv = nonce

      # Add auth tag and associated data
      cipher.auth_tag = auth_tag
      cipher.auth_data = associated_data

      # Decrypt
      cipher.update(cipher_text) + cipher.final
    end
  end
end
